"""
测试文件上传
"""

import json

import requests

test_file_path = "C:\\Users\\Yunlong\\Downloads\\WindTerm_2.7.0_Windows_Portable_x86_64.zip"


# 测试基本文件上传
def test_upload_file():
    url = "http://localhost:8000/upload/"
    file_path = "C:\\Users\\Yunlong\\Downloads\\0809-3.png"
    data = {"source": "测试文件", "target": "python,test"}

    files = {"file": ("test.png", open(file_path, "rb"), "image/png")}
    response = requests.post(url, files=files, data=data)

    print(response.status_code)
    print(response.json())
    assert response.status_code == 200
    assert "filename" in response.json()


test_upload_file()


# 测试多文件上传
def test_multi_upload():
    url = "http://localhost:8000/multi-upload/"
    files = [
        ("files", ("test1.jpg", open("test1.jpg", "rb"), "image/jpeg")),
        ("files", ("test2.png", open("test2.png", "rb"), "image/png")),
    ]
    response = requests.post(url, files=files)
    print(response.json())
    assert len(response.json()["results"]) == 2


# 测试带额外表单数据的文件上传
def test_upload_with_form_data():
    url = "http://localhost:8080/upload"
    data = {"source": "测试文件", "target": "python,test"}

    files = {"file": (test_file_path, open(test_file_path, "rb"))}

    response = requests.post(url, data=data, files=files, stream=True)

    # 处理流式进度更新
    for line in response.iter_lines():
        if line:  # 过滤掉keep-alive换行符
            try:
                # 解析进度数据 (假设服务器发送的是JSON格式)
                data = json.loads(line.decode("utf-8"))
                print(data)
                if "progress" in data:
                    print(f"当前进度: {data['progress']}%")
                elif "status" in data:
                    print(f"状态更新: {data['status']}")
            except json.JSONDecodeError:
                print(f"收到非JSON响应: {line.decode('utf-8')}")


# test_upload_with_form_data()


def upload_file_with_progress():
    url = "http://localhost:8080/upload"  # 替换为你的接口地址

    with open(test_file_path, "rb") as f:
        files = {"file": f}
        data = {"source": "client", "target": "server"}

        # 发起请求并流式读取响应
        with requests.post(url, files=files, data=data, stream=True) as response:
            for line in response.iter_lines():
                if line:
                    print(line.decode())  # 打印进度信息


# # 调用函数
# import httpx

# async def upload_file():
#     async with httpx.AsyncClient() as client:
#         files = {"file": open(test_file_path, "rb")}
#         data = {"source": "client", "target": "server"}
#         async with client.stream("POST", "http://localhost:8080/upload", files=files, data=data) as response:
#             async for chunk in response.aiter_bytes():
#                 print(chunk.decode())

# upload_file()
